package com.hmall.common.config;

import com.hmall.common.utils.RabbitMqHelper;
import com.hmall.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

import javax.validation.constraints.NotNull;

@Configuration
public class MqConfig {
    @Bean
    public MessageConverter messageConverter(){
        Jackson2JsonMessageConverter jackson2JsonMessageConverter=new Jackson2JsonMessageConverter();
        jackson2JsonMessageConverter.setCreateMessageIds(true);
        return new AutoMessageConverter(jackson2JsonMessageConverter);
    }
    @Bean
    public RabbitMqHelper rabbitMqHelper(RabbitTemplate rabbitTemplate){
        return new RabbitMqHelper(rabbitTemplate);
    }

    @RequiredArgsConstructor
    static class AutoMessageConverter implements MessageConverter {
        private final MessageConverter messageConverter;

        @Override
        public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
            Long userId = UserContext.getUser();
            messageProperties.setHeader("user_info",userId);
            return messageConverter.toMessage(o,messageProperties);
        }

        @Override
        public Object fromMessage(Message message) throws MessageConversionException {
            Object o = message.getMessageProperties().getHeader("user_info");
            if(o!=null){
                UserContext.setUser(Long.valueOf(o.toString()));
            }
            return messageConverter.fromMessage(message);
        }
    }

}
